package com.lsz.atm.ui.menu;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.common.config.Global;
import com.common.event.CommodityEvent;
import com.common.mvp.BaseMvpActivity;
import com.lsz.atm.R;
import com.lsz.atm.TemporaryDataUtil;
import com.lsz.atm.db.bean.CommodityBean;
import com.lsz.atm.db.bean.PackageBean;
import com.lsz.atm.db.dao_manager.CommodityManager;
import com.lsz.atm.db.dao_utils.DaoUtils;
import com.lsz.atm.dialog.ConfirmDialog;
import com.lsz.atm.event.StartOrderEvent;
import com.lsz.atm.json.ATMBean;
import com.lsz.atm.json.McTemporary;
import com.lsz.atm.json.MenuBean;
import com.lsz.atm.json.commodity.BundlesBean;
import com.lsz.atm.json.commodity.CommodityDataBean;
import com.lsz.atm.json.commodity.ProposalsBean;
import com.lsz.atm.ui.commodity.CommodityDetailActivity;
import com.lsz.atm.ui.menu.layout.MenuLayout;
import com.lsz.atm.ui.order.OrderListActivity;
import com.lsz.atm.viewutil.BigDecimalUtils;
import com.lsz.atm.viewutil.SpannableUtil;
import com.util_code.dialog.LoadingDialog;
import com.util_code.utils.DateUtils;
import com.util_code.widget.recyclerDecoration.PowerfulStickyDecoration;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

public class MenuListActivity extends BaseMvpActivity<MenuView, MenuPresent> implements MenuView, View.OnClickListener {

    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.ll_one_menu_up)
    LinearLayout llOneMenuUp;
    @BindView(R.id.rc_one_menu)
    RecyclerView rcOneMenu;
    @BindView(R.id.ll_one_menu_down)
    LinearLayout llOneMenuDown;
    @BindView(R.id.rc_commodity_list)
    RecyclerView rcCommodityList;
    @BindView(R.id.tv_commodity_title)
    TextView tvCommodityTitle;

    @BindView(R.id.tv_back)
    TextView tvBack;
    @BindView(R.id.tv_total_number)
    TextView tvTotalNumber;
    @BindView(R.id.tv_total_amount)
    TextView tvTotalAmount;
    @BindView(R.id.tv_select_ok)
    TextView tvSelectOk;

    private List<MenuBean> menuBeanList;
    private List<McTemporary> commodityList;
    private PowerfulStickyDecoration stickyDecoration;

    private ConfirmDialog confirmDialog;
    private LoadingDialog loadingDialog;

    private boolean isSelect = false;
    private MenuLayout menuLayout;
    private CommodityManager commodityInstance;

    public static void startActivity(Activity activity) {
        Intent intent = new Intent(activity, MenuListActivity.class);
        activity.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_menu_list;
    }

    @Override
    protected void setTranslateStatusBar(boolean barColor) {
        super.setTranslateStatusBar(false);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        tvBack.setOnClickListener(this);
        tvSelectOk.setOnClickListener(this);
        llOneMenuUp.setOnClickListener(this);
        llOneMenuDown.setOnClickListener(this);

        menuLayout = new MenuLayout(MenuListActivity.this);
        menuLayout.initRecyclerManager(rcOneMenu, rcCommodityList, commodityClicklistener);
        menuLayout.setMenuLayoutListener(menuLayoutListener);

        ATMBean atmBean = Global.getAtmBean();
        if (atmBean != null) {
            tvShopName.setText(atmBean.storeName);
        }

        if (loadingDialog == null) {
            loadingDialog = new LoadingDialog();
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        commodityInstance = DaoUtils.getCommodityInstance();
        List<MenuBean> menuList = Global.getMenuList();
        if (menuList != null && menuList.size() > 0) {
            getMenuListSuccess(menuList);
        }
        List<CommodityDataBean> commodityList = Global.getCommodityList();
        if (commodityList != null && commodityList.size() > 0) {
            getCommodityListSuccess(commodityList);
        }
        getPresenter().getMenuDataList(commodityList == null || commodityList.size() == 0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        commodityInstance.deleteAll();
//        commodityInstance.closeDB();
        EventBus.getDefault().unregister(this);
    }

    private MenuLayout.MenuLayoutListener menuLayoutListener = new MenuLayout.MenuLayoutListener() {
        @Override
        public void setCommodityTitle(String menuName) {
            tvCommodityTitle.setText(menuName);
        }
    };

    private MenuCommodityAdapter.CommodityClicklistener commodityClicklistener = new MenuCommodityAdapter.CommodityClicklistener() {

        @Override
        public void onCommodityDelete(ProposalsBean proposalsBean, int position) {
            List<CommodityBean> commodityById = commodityInstance.loadCommodityById(proposalsBean.id);
            if (commodityById == null || commodityById.size() == 0) {
                proposalsBean.cSelectNumber = 0;
                proposalsBean.totalPriceList = BigDecimalUtils.round(proposalsBean.priceSell, 2);
                menuLayout.notifiAdapter(proposalsBean);
                setSelectNumberAmount();
            } else if (commodityById.size() >= 2) {
                menuLayout.notifiAdapter(position, proposalsBean);
            } else {
                CommodityBean loadById = commodityById.get(0);
                loadById.cSelectNumber = loadById.cSelectNumber - 1;
                if (loadById.cSelectNumber == 0) {
                    commodityInstance.deleteObj(loadById);
                    proposalsBean.cSelectNumber = 0;
                    proposalsBean.totalPriceList = BigDecimalUtils.round(proposalsBean.priceSell, 2);
                } else {
                    loadById.totalPriceList = BigDecimalUtils.sub(loadById.totalPriceList, loadById.priceSell, 2);
                    commodityInstance.updateCommodity(loadById);
                    proposalsBean = TemporaryDataUtil.getProposalsBean(loadById);
                }
                menuLayout.notifiAdapter(proposalsBean);
                setSelectNumberAmount();
            }
        }

        @Override
        public void onCommodityAdd(ProposalsBean proposalsBean, int position) {
            List<BundlesBean> bundlesBeans = proposalsBean.bundles;
//            List<ChoicesBean> beanChoices = proposalsBean.getChoices();
//            || beanChoices != null && beanChoices.size() > 0
            if (bundlesBeans != null && bundlesBeans.size() > 0) {
                CommodityDetailActivity.startActivity(MenuListActivity.this, proposalsBean);
            } else {
                CommodityBean loadById = commodityInstance.loadById(proposalsBean.id);
                if (loadById == null) {
                    loadById = TemporaryDataUtil.getCommodityBean(proposalsBean);
                    loadById.cSelectNumber = loadById.cSelectNumber + 1;
                    if (loadById.cSelectNumber > 1) {
                        loadById.totalPriceList = BigDecimalUtils.add(loadById.totalPriceList, loadById.priceSell, 2);
                    }
                    commodityInstance.insertCommodityObject(loadById);
                } else {
                    loadById.cSelectNumber = loadById.cSelectNumber + 1;
                    if (loadById.cSelectNumber > 1) {
                        loadById.totalPriceList = BigDecimalUtils.add(loadById.totalPriceList, loadById.priceSell, 2);
                    }
                    commodityInstance.updateCommodity(loadById);
                }
                ProposalsBean proposals = TemporaryDataUtil.getProposalsBean(loadById);
                menuLayout.notifiAdapter(proposals);
                setSelectNumberAmount();
            }
        }

        @Override
        public void onItemClick(ProposalsBean proposalsBean, int position) {
            CommodityDetailActivity.startActivity(MenuListActivity.this, proposalsBean);
        }
    };

    private void setSelectNumberAmount() {
        List<CommodityBean> commodityBeanList = commodityInstance.loadAll();
        long totalNumber = 0L;
        String totalAmout = "0";
        if (commodityBeanList == null || commodityBeanList.size() == 0) {
            isSelect = false;
        } else {
            for (CommodityBean commodityBean : commodityBeanList) {
                if (commodityBean.cSelectNumber > 0) {
                    totalAmout = BigDecimalUtils.add(totalAmout, commodityBean.totalPriceList, 2);
                    List<PackageBean> packageList = DaoUtils.getPackageInstance().loadPackageByRandomId(commodityBean.randomId);
                    for (PackageBean packageBean : packageList) {
                        String tAmount = TemporaryDataUtil.getTotalAmount(packageBean.commodiTotalPrice, packageBean.commodiTotalPrice, commodityBean.cSelectNumber);
                        totalAmout = BigDecimalUtils.add(totalAmout, tAmount, 2);
                    }
                    totalNumber = totalNumber + commodityBean.cSelectNumber;
                    isSelect = true;
                } else {
                    isSelect = false;
                }
            }
        }
        if (totalNumber > 99) {
            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tvTotalNumber.getLayoutParams();
            layoutParams.width = totalNumber > 99 ? 78 : 58;
            layoutParams.height = totalNumber > 99 ? 78 : 58;
            tvTotalNumber.setLayoutParams(layoutParams);
        }
        tvTotalNumber.setText(totalNumber + "");
        String currency = getResources().getString(R.string.currency);
        String amount = currency + " " + totalAmout;
        SpannableString textSpannable = SpannableUtil.setTextSpannable(amount, 1, amount.length());
        tvTotalAmount.setText(textSpannable);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_back:
                EventBus.getDefault().post(new StartOrderEvent());
                finish();
                break;

            case R.id.tv_select_ok:
                if (isSelect) {
                    OrderListActivity.startActivity(this);
                } else {
                    ConfirmDialog.Builder builder = new ConfirmDialog.Builder(MenuListActivity.this);
                    confirmDialog = builder.setContentText("请添加商品").setConfirmListener(new ConfirmDialog.Builder.ConfirmClickListener() {
                        @Override
                        public void click(boolean b) {
                            confirmDialog.dismiss();
                        }
                    }).create();
                    confirmDialog.show();
                }
                break;

            case R.id.ll_one_menu_up:
                int[] pos = menuLayout.getRecyclerViewLastPosition();
                int iposs = pos[0] - 2;
                if (iposs <= 0) {
                    iposs = 0;
                }
                menuLayout.smoothMoveToPosition(rcOneMenu, iposs);
                break;

            case R.id.ll_one_menu_down:
                int[] pos1 = menuLayout.getRecyclerViewLastPosition();
                int ipos = pos1[0] + 2;
                if (ipos >= menuBeanList.size()) {
                    ipos = menuBeanList.size();
                }
                menuLayout.smoothMoveToPosition(rcOneMenu, ipos);
                break;

            default:
                break;
        }
    }

    @Override
    public void onShowLoading() {
        if (!loadingDialog.isVisible()) {
            loadingDialog.show(getSupportFragmentManager(), "loadingdialog");
        }
    }

    @Override
    public void onCloseLoading() {
        loadingDialog.dismissAllowingStateLoss();
    }

    @Override
    public void getMenuListSuccess(List<MenuBean> menuBeanList) {
        if (menuBeanList.size() > 0) {
            menuBeanList.get(0).menuSelect = true;
        }
        this.menuBeanList = menuBeanList;
        menuLayout.setMenuBeanList(menuBeanList);
    }

    @Override
    public void getCommodityListSuccess(List<CommodityDataBean> commodityBeanList) {
        commodityList = getCommodityList(commodityBeanList);
        if (commodityList.size() > 0 && commodityList.get(0) instanceof CommodityDataBean) {
            String menuName = "— " + ((CommodityDataBean) commodityList.get(0)).cTitle + " —";
            tvCommodityTitle.setText(menuName);
        }
        setSelectNumberAmount();
        menuLayout.setCommodityList(commodityList);
    }

    @Override
    public void onFail(int number) {
        if (number == 1) {
            loadingDialog.dismissAllowingStateLoss();
        }
    }

    private List<McTemporary> getCommodityList(List<CommodityDataBean> commodityBeanList) {
        List<CommodityBean> modityList = commodityInstance.loadAll();
        List<McTemporary> mcTemporary = new ArrayList<>();
        if (menuBeanList == null) {
            return mcTemporary;
        }
        for (CommodityDataBean commodityListBean : commodityBeanList) {
            for (MenuBean menuBean : menuBeanList) {
                if (TextUtils.equals(commodityListBean.menuId, menuBean.id)) {
                    CommodityDataBean listBean = new CommodityDataBean();
                    listBean.menuId = commodityListBean.menuId;
                    listBean.cTitle = menuBean.name;
                    mcTemporary.add(listBean);
                    break;
                }
            }
            for (ProposalsBean proposalsBean : commodityListBean.proposals) {
                String totalAmout = "0";
                proposalsBean.totalPriceList = proposalsBean.priceSell;
                if (modityList != null && modityList.size() > 0) {
                    for (CommodityBean commodityBean : modityList) {
                        if (TextUtils.equals(proposalsBean.id, commodityBean.id) && commodityBean.cSelectNumber > 0) {
                            proposalsBean.cSelectNumber = proposalsBean.cSelectNumber + commodityBean.cSelectNumber;
                            totalAmout = BigDecimalUtils.add(totalAmout, commodityBean.totalPriceList, 2);
                            proposalsBean.totalPriceList = totalAmout;
                        }
                    }
                }
                mcTemporary.add(proposalsBean);
            }
        }
        return mcTemporary;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(StartOrderEvent event) {
        finish();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(CommodityEvent event) {
        List<CommodityBean> modityList = commodityInstance.loadAll();
        if (modityList != null && modityList.size() > 0) {
            for (McTemporary temporary : commodityList) {
                if (temporary instanceof ProposalsBean) {
                    ProposalsBean proposalsBean = (ProposalsBean) temporary;
                    proposalsBean.isManySpe = false;
                    long selectNumber = 0;
                    String totalAmout = "0";
                    for (CommodityBean commodityBean : modityList) {
                        if (TextUtils.equals(proposalsBean.id, commodityBean.id)) {
                            selectNumber = selectNumber + commodityBean.cSelectNumber;
                            totalAmout = BigDecimalUtils.add(totalAmout, commodityBean.totalPriceList, 2);
                            proposalsBean.cSelectNumber = selectNumber;
                            proposalsBean.totalPriceList = totalAmout;
                            if (commodityBean.cSelectNumber == 0) {
                                commodityInstance.deleteObj(commodityBean);
                            } else {
                                commodityInstance.updateCommodity(commodityBean);
                            }
                            menuLayout.notifiAdapter(proposalsBean);
                        }
                    }
                }
            }
        }
        setSelectNumberAmount();
    }


}
